﻿using PlatformNetCore.Common;
using PlatformNetCore.Entity;
using PlatformNetCore.IRepository;
using PlatformNetCore.IService;
using System;

namespace PlatformNetCore.Service
{
    public class SmtpConfigService : ISmtpConfigService
    {
        private readonly ISmtpConfigRepository smtpConfigRepository;
        public SmtpConfigService(ISmtpConfigRepository _smtpConfigRepository)
        {
            smtpConfigRepository = _smtpConfigRepository;
        }

        #region 邮件服务配置
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultResponse<SmtpConfig> GetSmtpConfig()
        {
            ResultResponse<SmtpConfig> resultResponse = new ResultResponse<SmtpConfig>() { success = true, msg = CommonConst.Success };
            resultResponse.data = smtpConfigRepository.FirstOrDefault();
            if (resultResponse.data == null)
            {
                resultResponse.data = new SmtpConfig();
            }
            return resultResponse;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse SaveSmtpConfig(SmtpConfig model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if(string.IsNullOrWhiteSpace(model.ID))
            {
                model.ID = IdentityCreator.NextIdentity;
                model.AddDate = DateTime.Now;
                response.success = smtpConfigRepository.Add(model);
            }
            else
            {
                var o = smtpConfigRepository.FirstOrDefault();
                o.SmtpHost = model.SmtpHost;
                o.Account = model.Account;
                o.Email = model.Email;
                o.Port = model.Port;
                o.Pwd = string.IsNullOrWhiteSpace(model.Pwd)?o.Pwd:model.Pwd;
                o.IsSSL = model.IsSSL;
                o.UpdateDate = DateTime.Now;
                response.success = smtpConfigRepository.Update(o);
            }
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }
        #endregion
    }
}
